package com.itheima.homework;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @Author 王加鑫
 * @Date 2021/5/22 21:26
 * @Version 1.0
 * 4、【编号2005】有一个存放牛奶的箱子，送奶工将牛奶放入箱子，而用户从箱子中获取到牛奶，
 * 假设箱子只能存储一瓶牛奶，请编写程序模拟牛奶的存储和获取过程。
 */
public class Demo04 {
    public static void main(String[] args) {
        ArrayBlockingQueue abq = new ArrayBlockingQueue(1);
        Milk milk = new Milk();
        Thread thread1 = new Thread(new Custom(abq,milk));
        Thread thread2 = new Thread(new Person(abq,milk));
        thread1.start();
        thread2.start();

    }

}

class Milk{
    private int count;

    public Milk() {
        this(10);
    }

    public Milk(int count) {
        this.count = count;
    }


    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}


/**
 * 用户
 */
class Custom implements Runnable{

    private ArrayBlockingQueue abq;

    private Milk milk;

    public Custom(ArrayBlockingQueue abq,Milk milk) {
        this.abq = abq;
        this.milk = milk;
    }

    @Override
    public void run() {
        int count = milk.getCount();
        while (true){
            try {
                if(count == 0){
                    break;
                }
                count--;
                abq.put("牛奶");
                System.out.println("用户正在喝牛奶,还剩"+ count + "瓶牛奶");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }
}


/**
 * 送奶工
 */
class Person implements Runnable{

    private ArrayBlockingQueue abq;

    private Milk milk;

    public Person(ArrayBlockingQueue abq,Milk milk) {
        this.abq = abq;
        this.milk = milk;
    }


    @Override
    public void run() {
        int count = milk.getCount();
        while (true){
            try {
                if(count == 0){
                    break;
                }
                count--;
                abq.take();
                System.out.println("送奶工在送牛奶,还剩" + count + "瓶牛奶");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
